package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取 用户对象
        DtsAdmin admin = (DtsAdmin) principals.getPrimaryPrincipal();
        //获取角色id
        Integer[] roleIds = admin.getRoleIds();
        //根据角色id查询 角色和权限
        Set<String> roles = roleService.findRolesByIds(roleIds);
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);
        //创建返回值
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取前端传过来的 用户信息
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        //明文
        String password = new String(usernamePasswordToken.getPassword());
        //判 空
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new AuthenticationException("用户名和密码不能为空");
        }

        DtsAdmin admin = adminService.findAdmin(username);

        if(admin == null){
            throw new UnknownAccountException("未知的用户名");
        }
        //密文
        String passwordDb = admin.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(!passwordEncoder.matches(password, passwordDb)){
            throw new IncorrectCredentialsException("密码错误");
        }

        if(admin.getDeleted()){
            throw new LockedAccountException("账户已锁定");
        }


        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, password, admin.getUsername());
        return authenticationInfo;
    }
}
